import { PlusOutlined } from '@ant-design/icons';
import { Button, message, Drawer, Modal, FormInstance, Dropdown } from 'antd';
import React, { useState, useRef } from 'react';
import { useIntl, FormattedMessage, connect, ConnectProps } from 'umi';
import type { ConnectState } from '@/models/connect';
import type { CurrentUser } from '@/models/user';
import { PageContainer, FooterToolbar } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { ModalForm, ProFormText, ProFormTextArea } from '@ant-design/pro-form';
import type { ProDescriptionsItemProps } from '@ant-design/pro-descriptions';
import ProDescriptions from '@ant-design/pro-descriptions';
import UpdateForm from './components/UpdateForm';
import Cron from 'react-cron-antd';

import type { TableListItem } from './data.d';
import { queryData, saveOrUpdate, stopOrRestore, execution, removeData } from './service';

/**
 * 执行保存
 * @param fields
 */
const handleAdd = async (fields: TableListItem) => {
  const hide = message.loading('正在添加');
  try {
    await saveOrUpdate({ ...fields });
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

/**
 * 执行更新
 * @param fields
 */
const handleUpdate = async (fields: any) => {
  const hide = message.loading('正在更新');
  try {
    await saveOrUpdate(fields);
    hide();
    message.success('更新成功');
    return true;
  } catch (error) {
    hide();
    message.error('更新失败请重试！');
    return false;
  }
};

/**
 * 执行删除
 * @param selectedRows
 */
const handleRemove = async (selectedRows: TableListItem[]) => {
  const hide = message.loading('正在删除');
  if (!selectedRows) return true;
  try {
    const job_name = selectedRows.map((row) => row.job_name).join(',');
    const job_group = selectedRows.map((row) => row.job_group).join(',');
    await removeData(job_name, job_group);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 执行删除
 * @param selectedRow 
 * @returns 
 */
const handleRemoveOne = async (selectedRow: TableListItem) => {
  const hide = message.loading('正在删除');
  if (!selectedRow) return true;
  try {
    await removeData(selectedRow.job_name, selectedRow.job_group);
    hide();
    message.success('删除成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('删除失败，请重试');
    return false;
  }
};

/**
 * 停止或恢复
 * @param jobName 
 * @param jobGroup 
 * @param status 
 * @returns 
 */
const handleStopOrRestore = async (jobName: string, jobGroup: string, status: string) => {
  const hide = message.loading('正在执行');
  try {
    await stopOrRestore(jobName, jobGroup, status);
    message.success('执行成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('执行失败，请重试');
    return false;
  }
};

/**
 * 执行
 * @param jobName 
 * @param jobGroup 
 * @returns 
 */
const handleExecution = async (jobName: string, jobGroup: string) => {
  const hide = message.loading('正在执行');
  try {
    await execution(jobName, jobGroup);
    message.success('执行成功，即将刷新');
    return true;
  } catch (error) {
    hide();
    message.error('执行失败，请重试');
    return false;
  }
};

export type GlobalTableProps = {
  currentUser?: CurrentUser;
} & Partial<ConnectProps>;

const TableList: React.FC<GlobalTableProps> = (props) => {
  const formRef = useRef<FormInstance>();
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);
  /** 分布更新窗口的弹窗 */
  const [updateModalVisible, handleUpdateModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);

  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  /** 国际化配置 */
  const intl = useIntl();
  const { currentUser } = props;

  // 执行表达式
  const [value, setValue] = useState<any>();
  const [visible, setVisible] = useState<any>();
  const selectCronValue = (value: any) => {
    setValue(value)
    console.log(value)
    setVisible(false)
    formRef.current.setFieldsValue({
      cron_expression: value
    });
  }

  const columns: ProColumns<TableListItem>[] = [
    {
      title: '任务名称',
      dataIndex: 'job_name',
      tip: '任务名称',
      render: (dom, entity) => {
        return (
          <a
            onClick={() => {
              setCurrentRow(entity);
              setShowDetail(true);
            }}
          >
            {dom}
          </a>
        );
      },
    },
    {
      title: '任务分组',
      dataIndex: 'job_group',
      valueType: 'textarea',
    },
    {
      title: '执行类',
      dataIndex: 'job_class_name',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '执行时间',
      dataIndex: 'cron_expression',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: '开始时间',
      dataIndex: 'start_time',
      valueType: 'textarea',
      hideInSearch: true,
    },
    {
      title: <FormattedMessage id="pages.searchTable.titleOption" defaultMessage="操作" />,
      dataIndex: 'option',
      width: '220px',
      valueType: 'option',
      render: (_, record) => [
        <Button type="primary" size='small' key="config"
          style={{ display: currentUser?.authButton.includes('timTask:edit') ? 'block' : 'none' }}
          onClick={() => {
            handleUpdateModalVisible(true);
            setCurrentRow(record);
          }}>
          编辑
       </Button>,
        <Button type="primary" size='small' danger
          style={{ display: currentUser?.authButton.includes('timTask:del') ? 'block' : 'none' }}
          onClick={async () => {
            Modal.confirm({
              title: '删除任务',
              content: '确定删除该任务吗？',
              okText: '确认',
              cancelText: '取消',
              onOk: () => {
                const success = handleRemoveOne(record);
                if (success) {
                  if (actionRef.current) {
                    actionRef.current.reload();
                  }
                }
              },
            });
          }}>
          删除
      </Button>,
        <Button type="primary" size='small' key="config"
          style={{ display: currentUser?.authButton.includes('timTask:execution') ? 'block' : 'none' }}
          onClick={() => {
            const success = handleExecution(record.job_name, record.job_group)
            if (success) {
              if (actionRef.current) {
                actionRef.current.reload();
              }
            }
          }}>
          执行
   </Button>,
        <Button type="primary" size='small' style={{ display: (record.trigger_state == 'PAUSED' && currentUser?.authButton.includes('timTask:stopOrRestore')) ? 'block' : 'none' }} danger onClick={() => {
          const success = handleStopOrRestore(record.job_name, record.job_group, 'restore');
          if (success) {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}>
          恢复
    </Button>,
        <Button type="primary" size='small' style={{ display: (record.trigger_state != 'PAUSED' && currentUser?.authButton.includes('timTask:stopOrRestore')) ? 'block' : 'none' }} onClick={() => {
          const success = handleStopOrRestore(record.job_name, record.job_group, 'stop');
          if (success) {
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}>
          停止
  </Button>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem>
        headerTitle={intl.formatMessage({
          id: 'pages.searchTable.title',
          defaultMessage: '查询表格',
        })}
        actionRef={actionRef}
        rowKey="id"
        search={{
          labelWidth: 120,
        }}
        toolBarRender={() => [
          <Button
            type="primary"
            key="primary"
            style={{ display: currentUser?.authButton.includes('timTask:add') ? 'block' : 'none' }}
            onClick={() => {
              handleModalVisible(true);
            }}
          >
            <PlusOutlined /> <FormattedMessage id="pages.searchTable.new" defaultMessage="新建" />
          </Button>,
        ]}
        request={
          (params, sorter, filter) => queryData(params).then(res => {
            const result = {
              data: res.data.rows,
              total: res.data.total,
              success: true
            }
            return result
          })
        }
        columns={columns}
        rowSelection={{
          onChange: (_, selectedRows) => {
            setSelectedRows(selectedRows);
          },
        }}
      // toolBarRender={false}
      // search={false}
      />
      {selectedRowsState?.length > 0 && (
        <FooterToolbar
          extra={
            <div>
              <FormattedMessage id="pages.searchTable.chosen" defaultMessage="已选择" />{' '}
              <a style={{ fontWeight: 600 }}>{selectedRowsState.length}</a>{' '}
              <FormattedMessage id="pages.searchTable.item" defaultMessage="项" />
            </div>
          }
        >
          <Button
            style={{ display: currentUser?.authButton.includes('timTask:del') ? 'block' : 'none' }}
            onClick={async () => {
              Modal.confirm({
                title: '删除任务',
                content: '确定删除该任务吗？',
                okText: '确认',
                cancelText: '取消',
                onOk: () => {
                  const success = handleRemove(selectedRowsState);
                  if (success) {
                    setSelectedRows([]);
                    actionRef.current?.reloadAndRest?.();
                  }
                },
              });
            }}
          >
            <FormattedMessage id="pages.searchTable.batchDeletion" defaultMessage="批量删除" />
          </Button>
        </FooterToolbar>
      )}
      <ModalForm
        title={intl.formatMessage({
          id: '新建任务',
          defaultMessage: '新建任务',
        })}
        width="600px"
        formRef={formRef}
        visible={createModalVisible}
        onVisibleChange={handleModalVisible}
        onFinish={async (value) => {
          const success = await handleAdd(value as TableListItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
            formRef.current?.resetFields();
          }
        }}
      >
        <ProFormText
          label='任务名称'
          rules={[
            {
              required: true,
              message: '任务名称',
            },
          ]}
          width="xl"
          name="job_name"
          placeholder="请输入任务名称"
        />
        <ProFormText
          label='任务分组'
          rules={[
            {
              required: true,
              message: '任务分组',
            },
          ]}
          width="xl"
          name="job_group"
          placeholder="请输入任务分组"
        />
        <ProFormText
          label='执行类'
          rules={[
            {
              required: true,
              message: '执行类',
            },
          ]}
          width="xl"
          name="job_class_name"
          placeholder="请输入执行类"
        />
        <Dropdown
          visible={visible}
          onVisibleChange={visible => visible}
          trigger={['click']}
          placement="bottomLeft"
          overlay={<Cron onOk={selectCronValue} value={value} />}
        >
          <div>
            <div style={{float:'left',width:'70%'}}>
              <ProFormText
                label='执行时间'
                rules={[
                  {
                    required: true,
                    message: '执行时间',
                  },
                ]}
                width="xl"
                name="cron_expression"
                placeholder="请输入执行时间"
              />
            </div>
            <div style={{float:'left',width:'30%',padding:'30px 0 0 10px'}}>
              <Button type="primary" onClick={(value) => {
                setVisible(true)
              }}>获取表达式</Button>
            </div>
            <div style={{clear:'both'}}></div>
          </div>
          {/* <Input value={value} onClick={(value) => {
              setVisible(true)
            }} /> */}
        </Dropdown>

        <ProFormTextArea width="xl" name="description" label='任务描述'
          placeholder="请输入任务描述"
        />
      </ModalForm>
      <UpdateForm
        onSubmit={async (value) => {
          const success = await handleUpdate({ ...value, old_job_name: currentRow?.job_name,old_job_group:currentRow?.job_group });
          // const success = await handleUpdate({...value,id:currentRow?.id});
          if (success) {
            handleUpdateModalVisible(false);
            setCurrentRow(undefined);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
        onCancel={() => {
          handleUpdateModalVisible(false);
          setCurrentRow(undefined);
        }}
        updateModalVisible={updateModalVisible}
        values={currentRow || {}}
      />
      <Drawer
        width={600}
        visible={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.name && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.name}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.name,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer>
    </PageContainer>
  );
};

// export default TableList;
export default connect(({ user, loading }: ConnectState) => ({
  currentUser: user.currentUser,
}))(TableList);